package com.nexus.all.utils.wxUtils;

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XmlUtil {

    /**
     * 简单解析xml
     *
     * @param in
     * @return
     */
    public static Map<String, Object> parseXML(InputStream in) {
        Map<String, Object> map = new HashMap<>();
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            Element root = document.getRootElement();
            Iterator iterator = root.elementIterator();
            while (iterator.hasNext()) {
                Element element = (Element) iterator.next();
                map.put(element.getName(), element.getStringValue());

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return map;
    }


    /**
     * 将 Java Bean 转化为 XML
     *
     * @param bean {@link Object}
     * @param cls  传入对象的字节码
     * @return XML 字符串
     */
    public static <T> String beanToXml(Object bean, Class<T> cls) {
        XStream stream = new XStream();
        stream.processAnnotations(cls);
        return stream.toXML(bean);
    }

    /**
     * 将 Java Bean 转化为 XML
     *
     * @param bean {@link Object}
     * @return XML 字符串
     */
    public static String beanToXml(Object bean) {
        return beanToXml(bean, bean.getClass());
    }
}
